package goutils

import (
	"fmt"
	"io"
	"os"
	"path"
	"time"
	"gitee.com/lipanbin/goutils/logs"
)

type FileLog struct {
	Path  string // 文件存储目录
	Queue *Queue // 持久化队列
}

// 实例化一个日志文件操作对象
func NewFileLog(path string) *FileLog {
	fl := &FileLog{Path: AbsPath(path), Queue: NewQueue(0)}
	go fl.log_worker()

	return fl
}

// 队列持久化任务
func (fl *FileLog) log_worker() {
	for {
		if fl.Queue.IsEmpty() {
			time.Sleep(1 * time.Second)
			continue
		}
		f, err := fl.GetFile()
		if err != nil {
			logs.Error("Game Log Write Err: %v", err)
			time.Sleep(3 * time.Second)
			continue
		}

		for !fl.Queue.IsEmpty() {
			val, err1 := fl.Queue.Get(0)
			if err1 != nil {
				logs.Error("Game Log Write Err: %v", err1)
				break
			}

			_, err2 := io.WriteString(f, val.(string))
			if err2 != nil {
				logs.Error("Game Log Write Err: %v", err2)
				break
			}
		}
		f.Close()
	}
}

// 异步写入log文件
func (fl *FileLog) AsyncAddGameLog(format string, a ...interface{}) {
	now := time.Now()
	str := fmt.Sprintf("%d-%02d-%02d %02d:%02d:%02d %v \n",
		now.Year(),
		now.Month(),
		now.Day(),
		now.Hour(),
		now.Minute(),
		now.Second(),
		fmt.Sprintf(format, a...))
	fl.Queue.PutNoWait(str)
}

// 获取日志文件
func (fl *FileLog) GetFile() (*os.File, error) {
	now := time.Now()

	pathname := fl.Path
	filename := fmt.Sprintf("%d-%02d-%02d.txt",
		now.Year(),
		now.Month(),
		now.Day())

	if err := Mkdir(pathname); err != nil {
		return nil, err
	}

	filepath := path.Join(pathname, filename)

	return CreateFile(filepath)
}
